import base64
import urllib
import requests
import os
import time

API_KEY = os.getenv("OCR_API_KEY")
SECRET_KEY = os.getenv("OCR_SECRET_KEY")


def mock(img_path):
    print(img_path)
    base64 = _get_file_content_as_base64(img_path)
    time.sleep(3)
    return f"{{'text': 'this is a mock api, slept 3s, got {img_path=}, {base64[:20]=}'}}"


def general(img_path):
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + _get_access_token()
    base64 = _get_file_content_as_base64(img_path)
    payload = f"image={base64}&detect_direction=false&detect_language=false&paragraph=false&probability=false"
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.text


def medical_report_detection(img_path):
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/medical_report_detection?access_token=" + _get_access_token()
    base64 = _get_file_content_as_base64(img_path)
    payload = f'image={base64}&location=false&probability=false'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.text


def health_report(img_path):
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/health_report?access_token=" + _get_access_token()
    base64 = _get_file_content_as_base64(img_path)
    payload = f'image={base64}&location=false&probability=false'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.text


def _get_file_content_as_base64(path, urlencoded=True):
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content


def _get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))
